package com.cloud.wms.base;

import android.os.Message;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.CallSuper;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.LinearSmoothScroller;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.cloud.core.base.BasePresenter;
import com.cloud.core.widget.decoration.TopSmoothScroller;
import com.cloud.wms.R;
import com.cloud.wms.http.observer.SimpleObserver;
import com.cloud.wms.tools.PageHelper;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Observable;

/**
 * @Author:Chen
 * @Date: 2021-01-14 14:12
 * @Description:
 */
public abstract class BaseListActivity<T, P extends BasePresenter> extends BaseActivity<P> {
    @BindView(R.id.rv_list)
    protected RecyclerView rvList;
    protected SmartRefreshLayout refreshLayout;
    protected BaseQuickAdapter<T, BaseViewHolder> mAdapter;
    protected int page = 0;
    private boolean isRefreshing = true;

    @Override
    @CallSuper
    protected void initEvent() {
        rvList.setLayoutManager(getLayoutManager());
        mAdapter = new BaseQuickAdapter<T, BaseViewHolder>(getItemResId()) {
            @Override
            protected void convert(BaseViewHolder helper, T item) {
                bindItemData(helper, item);
            }
        };
        mAdapter.setOnItemClickListener((adapter, view, position) -> itemClickListener(mAdapter, view, position));
        rvList.setItemAnimator(new DefaultItemAnimator());
        if (itemDecoration() != null)
            rvList.addItemDecoration(itemDecoration());
        rvList.setAdapter(mAdapter);

        if (isRefresh()) {
            refreshLayout = (SmartRefreshLayout) findViewById(R.id.refreshLayout);
            refreshLayout.setEnableRefresh(isRefresh());
            refreshLayout.setEnableLoadMore(isLoadMore());

            refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
                @Override
                public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                    refreshLayout.getLayout().postDelayed(() -> loadListData(page = 0), 100);
                }

                @Override
                public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                    refreshLayout.getLayout().postDelayed(() -> loadListData(++page), 100);
                }
            });
        }
    }

    /**
     * 加载列表数据
     *
     * @param page
     */
    @CallSuper
    protected void loadListData(int page) {
        if (isRefreshing)
            refreshLayout.autoRefresh();
    }

    /**
     * 是否刷新
     *
     * @return
     */
    protected boolean isRefresh() {
        return false;
    }

    /**
     * 是否加载更多
     *
     * @return
     */
    protected boolean isLoadMore() {
        return false;
    }

    @Override
    @CallSuper
    public void onSuccess(Message message) {
        if (isRefresh()) {
            isRefreshing = true;
            switch (message.what) {
                case PageHelper.LIST_NEW_DATA:
                    refreshList(((List<T>) message.obj));
                    break;
                case PageHelper.LIST_NEXT_DATA:
                    loadMoreList(((List<T>) message.obj));
                    break;
            }
        }
    }

    /**
     * 刷新列表方法
     */
    protected void refreshList(List<T> data) {
        refreshLayout.finishRefresh();
        refreshLayout.resetNoMoreData();//恢复上拉状态
        if (data == null || data.isEmpty()) {
            mAdapter.setNewInstance(new ArrayList<>());
            mAdapter.setEmptyView(getEmptyDataView());
            return;
        }
        if (data.size() < PageHelper.PAGE_SIZE) {
            refreshLayout.finishLoadMoreWithNoMoreData();//设置之后，将不会再触发加载事件
        }
        mAdapter.setNewInstance(data);
    }

    @Override
    public void error(String msg) {
        super.error(msg);
        if (refreshLayout != null) refreshLayout.finishRefresh(false);
    }

    /**
     * 加载更多方法
     */
    protected void loadMoreList(List<T> data) {
        if (data == null || data.isEmpty()) {
            refreshLayout.finishLoadMoreWithNoMoreData();//设置之后，将不会再触发加载事件
            return;
        }
        mAdapter.addData(data);
        if (data.size() < PageHelper.PAGE_SIZE) {
            info("数据全部加载完毕！");
            refreshLayout.finishLoadMoreWithNoMoreData();//设置之后，将不会再触发加载事件
        } else {
            refreshLayout.finishLoadMore();
        }
    }

    /**
     * 空视图
     *
     * @return
     */
    protected View getEmptyDataView() {
        View notDataView = getLayoutInflater().inflate(com.cloud.core.R.layout.layout_empty, rvList, false);
        notDataView.setOnClickListener(v -> {
            isRefreshing = false;
            loadListData(page = 0);
        });
        return notDataView;
    }

    /**
     * 错误视图
     *
     * @return
     */
    protected View getErrorView() {
        View errorView = getLayoutInflater().inflate(com.cloud.core.R.layout.layout_error, rvList, false);
        errorView.setOnClickListener(v -> {
            isRefreshing = false;
            loadListData(page = 0);
        });
        return errorView;
    }

    /**
     * 提供item布局
     *
     * @return
     */
    protected abstract @LayoutRes
    int getItemResId();

    /**
     * 提供布局管理器，默认垂直布局
     *
     * @return
     */
    protected RecyclerView.LayoutManager getLayoutManager() {
        return new LinearLayoutManager(mContext);
    }

    /**
     * 提供item布局数据绑定
     *
     * @return
     */
    protected abstract void bindItemData(BaseViewHolder helper, T item);

    /**
     * item点击事件
     *
     * @param mAdapter
     * @param view
     * @param position
     */
    protected void itemClickListener(BaseQuickAdapter<T, BaseViewHolder> mAdapter, View view, int position) {

    }

    /**
     * item分割线
     */
    protected RecyclerView.ItemDecoration itemDecoration() {
        return null;
    }

    /**
     * 滑动到指定列表位置
     *
     * @param position
     */
    protected void scrollToPosition(RecyclerView recyclerView, int position) {
        Observable
                .timer(300, TimeUnit.MILLISECONDS)
                .subscribe(new SimpleObserver<Long>() {
                    @Override
                    public void onSuccess(Long aLong) {
                        LinearSmoothScroller scroller = new TopSmoothScroller(BaseListActivity.this);
                        scroller.setTargetPosition(position);
                        recyclerView.getLayoutManager().startSmoothScroll(scroller);
                    }
                });
    }
}
